package com.first.xiinn.action;

import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import com.first.core.common.QueryFilter;
import com.first.core.util.StringUtil;
import com.first.core.web.action.BaseAction;
import com.first.module.acm.model.AppRole;
import com.first.xiinn.model.BookManager;
import com.first.xiinn.model.User;
import com.first.xiinn.service.UserService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class UserAction extends BaseAction {

	@Resource
	private UserService userService;
	private User user;

	private String userName;

	private String password;

	private String query;
	
	private String id;
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	/**
	 * 用户登陆
	 * 
	 * @return
	 */
	public String login() {
		User loginUser = null;
		HttpServletRequest req = getRequest();

		loginUser = userService.getUser(userName);
		if (null == loginUser) {
			req.setAttribute("errorMsg", "用户信息不存在，请重新输入！");
			return "login";// 用户不存在
		}

		if (loginUser.getPassword().equals(StringUtil.encryptSha256(password))) {
			HttpSession session = getSession();
			session.setAttribute("member", loginUser);
		} else {
			req.setAttribute("errorMsg", "用户信息不存在或密码错误，请重新输入！");
			return "login";// 用户密码错误
		}

		return SUCCESS;
	}

	public String forgotten() {
		HttpServletRequest r = getRequest();
		HttpSession session = r.getSession();
		String name = r.getParameter("name");
		String email = r.getParameter("email");
		if (name == null || name.equals("") || email == null
				|| email.equals("")) {
			session.setAttribute("ERROR", "用户名或邮箱不能为空!");
			return SUCCESS;
		} else {
			List list = userService.getforgotten(name, email);
			if (list.isEmpty()) {
				session.setAttribute("ERROR", "验证错误!");
			} else {
				session.setAttribute("ERROR", "验证正确!");
			}
			return SUCCESS;
		}
	}

	/**
	 * 模糊查询作者
	 * 
	 * @return
	 */
	public String searchAutor() {
		List list = this.userService.searchAutor(query);
		Gson gson = new Gson();
		StringBuffer sb = new StringBuffer("{totalCount:123,result:");
		sb.append(gson.toJson(list));
		sb.append("}");
		setJsonString(sb.toString());
		return "success";
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getQuery() {
		return query;
	}

	public void setQuery(String query) {
		this.query = query;
	}

	public String register() {
		User u = new User();
		HttpServletRequest r = getRequest();
		HttpSession session = r.getSession();
		String userName = r.getParameter("username");
		String password = r.getParameter("password");
		String confirmPassword = r.getParameter("confirmPassword");
		String sex = r.getParameter("sex");
		String email = r.getParameter("email");
		String address = r.getParameter("address");
		String phone = r.getParameter("phone");
		u.setName(userName);
		u.setPassword(password);
		u.setSex(sex);
		u.setEmail(email);
		u.setAddress(address);
		u.setPhone(phone);
		if (userName == null || userName.equals("") || password == null
				|| password.equals("")) {
			session.setAttribute("right", "用户名或密码不能为空!");
			return SUCCESS;
		} 
		if (!password.equals(confirmPassword)) {
			session.setAttribute("right", "两次输入的密码不一致请重新输入!");
			return SUCCESS;
		}else{
			this.userService.getregister(u);
			session.setAttribute("right", "添加成功!");
			return SUCCESS;
		}
	}
	
	public String list()
    {
        QueryFilter filter = new QueryFilter(getRequest());
        List<User> list = this.userService.getAll(filter);

        Type type = new TypeToken<List<User>>(){}.getType();
        StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
          .append(filter.getPagingBean().getTotalItems()).append(",result:");
        Gson gson = new Gson();
        buff.append(gson.toJson(list, type));
        buff.append("}");
        this.jsonString = buff.toString();
        System.out.println("=========="+jsonString);
        
        return "success";
    }
	
	  public String get()
	  {
	    User user = (User)this.userService.get(this.id);
	    Gson gson = new Gson();

	    StringBuffer sb = new StringBuffer("{success:true,data:");
	    sb.append(gson.toJson(user));
	    sb.append("}");
	    setJsonString(sb.toString());

	    return "success";
	  }
	  
	  public String save()
	  {
		  if(user.getId().equals("")){
			   user.setId(null);
	        }
		    userService.save(this.user);
	        if(user != null){
	            setJsonString("{success:true}");
	        } else{
	            setJsonString("{success:false}");
	        }
	        return "success";
	  }
	
}
